<!DOCTYPE html>
<html lang="zh-cmn-Hans" prefix="og: http://ogp.me/ns#" class="han-init">
<head>
  <meta charset="utf-8">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <link rel="icon" href="http://upeng.github.io/favicon.ico">
  <title>upeng</title>
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/lib/fancybox/jquery.fancybox-1.3.4.css">
  <!--在这里倒入jquery 方便处理部分页面的jquery-->
  <script src="https://cdn.staticfile.org/jquery/1.7/jquery.min.js" type="text/javascript" ></script>
</head>

<body>
	<header class="site-header navfixed-false">
  <div class="container">
      <h1><a href="/" title="upeng"><span class="octicon octicon-mark-github"></span> upeng</a></h1>
      <nav class="site-header-nav" role="navigation">
        
              
              <a href="/"  class=" site-header-nav-item hvr-underline-from-center" title="Home">Home</a>
        
              
              <a href="/categories/"  class=" site-header-nav-item hvr-underline-from-center" title="Categories">Categories</a>
        
              
              <a href="/bookmark/"  class=" site-header-nav-item hvr-underline-from-center" title="Bookmark">Bookmark</a>
        
              
              <a href="http://shareup.sinaapp.com"  class=" site-header-nav-item hvr-underline-from-center" title="Share">Share</a>
        
              
              <a href="/about/"  class=" site-header-nav-item hvr-underline-from-center" title="About">About</a>
        
      </nav>
  </div>
</header>

	
<section class="collection-head geopattern" data-pattern-id="PHP设计模式-工厂模式" >
    <div class="container">
        <div class="collection-title">
            <h1 class="collection-header">
                PHP设计模式-工厂模式
            </h1>
            
                <div class="collection-info">
                    <span class="meta-info">
                        <span class="octicon octicon-calendar"></span>
                        <time datetime="2015-10-12T14:12:00.000Z" itemprop="datePublished">2015-10-12</time>
                    </span>
                    
                        <span class="meta-info">
                            <span class="octicon octicon-file-directory"></span>
                            <a href='/categories/PHP/' title=''>PHP</a>
                        </span>
                    
                </div>
            
        </div>
    </div>
</section>
	<section class="container">
    <div class="columns">
        <!-- -->
        <div class="column three-fourths">
            <article class="article-content markdown-body">
                <h2 id="简单工厂模式"><a href="#简单工厂模式" class="headerlink" title="简单工厂模式"></a>简单工厂模式</h2><p>直接上代码，直观了解工厂模式！</p>
<pre><code>&lt;?php
//接口，是客户端和服务端共同遵守的开发规范
interface db
{
    public function conn(){};
}

//服务端
class Dbmysql implements db
{
    public function conn()
    {
        echo &#39;connected the mysql&#39;;
    }
}

class Dbsqlite implements db
{
    public function conn()
    {
        echo &#39;connected the sqlite&#39;;
    }
}

//客户端 
$mysql = new Dbmysql();
$mysql-&gt;conn();

$sqlite = new Dbsqlite();
$sqlite-&gt;conn();

//如果服务端不想让客户端知道自己内部类的实现细节，统一一个固定的入口，这样就是我们所说的
//使用方知道的越少越好！将上述两个类封装起来

//服务端，开发接口Dbconnect::type(@param)

class Dbconnect 
{
    public static function type($type)
    {
        if ($type == &#39;mysql&#39;)
        {
            return new Dbmysql();
        }
        else if ($type == &#39;sqlite&#39;)
        {
            return new Dbsqlite();
        }
        else
        {
            throw new Exception(&quot;Error type is not exist&quot;, 1);

        }
    }
}

//客户端
$mysql = Dbconnect::type(&#39;mysql&#39;);
$mysql-&gt;conn();

$sqlite = Dbconnect::type(&#39;sqlite&#39;);
$sqlite-&gt;conn();
</code></pre><p>在我们使用围脖的接口时，和这个有点类似，一个业务需求给你一个方法如showbatch(),friendship(),show()；当然他们是某个类的静态方法，我们不需要知道它是如何具体实现的，只要知道，当我们传递合适的参数，使用这个接口，就可以获得自己想要的数据即可</p>
<p><code>Q:现在如果需要连接oracle、PDO、SqlServer，怎么办？当然php可以直接修改服务端的代码，增加else if，但是对于java,c++而言，如果修改代码，还需要再次编译，这是非常耗时的!</code></p>
<blockquote>
<p><strong>在面向对象设计（OOD）设计法则中，重要的开闭原则：对于修改是封闭，对于扩展是开放的</strong></p>
</blockquote>
<h2 id="工厂方法"><a href="#工厂方法" class="headerlink" title="工厂方法"></a>工厂方法</h2><p><strong>注意开闭原则</strong><br>//<strong>服务端</strong></p>
<pre><code>interface Factory
{
    public function createDb(){};
}

class mysqlFactory implements Factory
{
    public function createDb()
    {
        return new Dbmysql();
    }
}

class sqliteFactory implements Factory
{
    public function createDb()
    {
        return new Dbsqlite();
    }
}

//**客户端**
//由于开放了两个接口，一个是创建数据库，一个是连接数据库

$fact = new mysqlFactory();
$db = $fact-&gt;createDb();
$db-&gt;conn();

$fact = new sqliteFactory();
$db-&gt;$fact-&gt;createDb();
$db-&gt;conn(); 

//现在如果新增了oracle数据库连接，就可以扩展oracle，不需要修改代码，扩展如下：

class Dboracle implements db()
{
    public function conn()
    {
        echo &#39;connected oracle database&#39;;
    }
}
class oracleFactory implements Factory
{
    public function createDb()
    {
        return new Dboracle();
    }
}


$fact = new oracleFactory();
$db = $fact-&gt;createDb();
$db-&gt;conn();
</code></pre>
            </article>
            
                <div class="share">
                    <!--开启分享-->
<div class="share-component" data-disabled="google,twitter,facebook" data-description=""></div>

<script src="/js/share.min.js"></script>

                </div>    
            
            
                
<div class="comments">
	<div class="ds-thread" data-thread-key="php-design-model" data-title="PHP设计模式-工厂模式" data-url="http://upeng.github.io/2015/10/12/php-design-model/"></div>
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"upeng"};
		(function() {
			var ds = document.createElement('script');
			ds.type = 'text/javascript';ds.async = true;
			ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
			ds.charset = 'UTF-8';
			(document.getElementsByTagName('head')[0]
			 || document.getElementsByTagName('body')[0]).appendChild(ds);
		})();
	</script>
</div>

            
        </div>
        <div class="column one-fourth">
            
                
                


<h3>Post Directory</h3>

<div id="post-directory-module">
	<section class="post-directory">
		<p><strong class="toc-title">文章目录</strong></p>
		<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#简单工厂模式"><span class="toc-text">简单工厂模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#工厂方法"><span class="toc-text">工厂方法</span></a></li></ol>
	</section>
</div>
            
        </div>
    </div>
</section>

<footer class="container">
    <div class="site-footer" role="contentinfo">
        <div class="copyright left mobile-block">
                © 2016
                <span title="yupeng">yupeng</span>
                <a href="javascript:window.scrollTo(0,0)" class="right mobile-visible">TOP</a>
        </div>

        <ul class="site-footer-links right mobile-hidden">
            <li>
                <a href="javascript:window.scrollTo(0,0)" >TOP</a>
            </li>
        </ul>

        <a href="https://github.com/upeng" target="_blank" aria-label="view source code">
            <span class="mega-octicon octicon-mark-github" title="GitHub"></span>
        </a>

        <ul class="site-footer-links mobile-hidden">
            
                  
                  <li>
                    <a href="/"  title="Home">Home</a>
                  </li>
            
                  
                  <li>
                    <a href="/categories/"  title="Categories">Categories</a>
                  </li>
            
                  
                  <li>
                    <a href="/bookmark/"  title="Bookmark">Bookmark</a>
                  </li>
            
                  
                  <li>
                    <a href="http://shareup.sinaapp.com"  title="Share">Share</a>
                  </li>
            
                  
                  <li>
                    <a href="/about/"  title="About">About</a>
                  </li>
            
            <li>
                <a href="/atom.xml">
                    <span class="octicon octicon-rss" style="color:orange;"></span>
                </a>
            </li>
        </ul>
    </div>
</footer>


		<script src="/js/geopattern.js"></script>

		
			<script src="/js/toc.js"></script>
		

		<script src="/js/highlight.pack.js"></script>
		<script src="/lib/fancybox/jquery.fancybox-1.3.4.pack.js"></script>

		<script src="/js/index.js"></script>

		 <script src="/js/popular_repo.js"></script> 

	</body>
</html>